package com.example.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.common.Result;
import com.example.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String url = request.getRequestURL().toString();
        log.info("请求的url:{}", url);
        if (url.contains("login")) {
            log.info("登陆操作，放行");
            return true;
        }
        String jwt = request.getHeader("X-Token");
        if (!StringUtils.hasLength(jwt)) {
            log.info("请求头为空，返回未登陆的错误信息");
            Result error= Result.error("NOT_LOGIN");
            String nologin= JSONObject.toJSONString(error);
            response.getWriter().write(nologin);
            return false;
        }
        //快捷键ctrl+alt=t,快速生成try catch;
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("jwt令牌校验失败，返回未登录的错误信息");
            Result error= Result.error("NOT_LOGIN");
            String nologin= JSONObject.toJSONString(error);
            response.getWriter().write(nologin);
            return false;
        }
        log.info("令牌校验成功！");
        return true;
    }
}
